<template>
  <sv-page>
    <view class="doneexam">
      <view
        class="done-exam-item card"
        v-for="(item, index) in doneExamData"
        :key="item.exam_id"
        @click="onExam(item, index)"
      >
        <view class="done-exam-item-title">
          <text>题库：</text>
          <text class="text-grey">{{ buyLibMap[item.from_lib] }}</text>
          <view class="type-tag">{{ examConfig.paperTypeDict[item.exam_type] }}</view>
        </view>
        <rich-text :nodes="item.exam_title"></rich-text>
      </view>
    </view>
  </sv-page>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
import { store } from '@/uni_modules/sv-id-pages/common/store'
import { buyLibList, doneExamList } from '@/service/api/record'
import { cloneDeep } from 'lodash'
import examConfig from '@/uni_modules/sv-exam/components/sv-exam/config.js'

const doneExamData = ref([])
const buyLibMap = ref({})

onPullDownRefresh(async () => {
  await handleInit()
  uni.stopPullDownRefresh()
})

onLoad(async () => {
  uni.showLoading({ title: '加载中' })
  await handleInit()
  uni.hideLoading()
})

async function handleInit() {
  const doneExamRes = await doneExamList({ user_id: store.userInfo._id })
  doneExamData.value = doneExamRes.data || []
  const buyLibRes = await buyLibList({ user_id: store.userInfo._id })
  buyLibMap.value = buyLibRes.data.reduce((acc, cur) => {
    acc[cur.lib_id] = cur.lib_name
    return acc
  }, {})
}

function onExam(item, index) {
  uni.navigateTo({
    url: '/pages/exam/simple-exam',
    success(res) {
      res.eventChannel.emit('e-transmit-exams', {
        title: '刷题记录',
        item,
        index,
        data: cloneDeep(doneExamData.value) // 深拷贝，防止数据污染
      })
    }
  })
}
</script>

<style lang="scss">
.doneexam {
  padding: 24rpx;
  box-sizing: border-box;

  .done-exam-item {
    border-radius: 24rpx;
    margin-bottom: 24rpx;
    padding: 20rpx 24rpx;
    box-sizing: border-box;

    @include useTheme {
      background-color: getTheme('sv-background-highlight-color');
    }

    &-title {
      margin-bottom: 20rpx;

      .type-tag {
        float: right;
        background-color: #01beff;
        color: #ffffff;
        padding: 2rpx 8rpx;
        font-size: 12px;
        border-radius: 8rpx;
      }
    }
  }
}
</style>
